package mysql

import (
	"fmt"
	"goconfcenter/models"
	"goconfcenter/pkg/Util"
	"goconfcenter/service/dto/bus"

	"go.uber.org/zap"
)

type RoleDao struct {
}

func RoleDaoInstance() *RoleDao {
	return &RoleDao{}
}

func (c *RoleDao) PageByQuery(params *bus.RoleQuery) ([]*models.RolePoJo, int64) {
	var total int64
	whereSql := " 1= 1 "
	data := make([]*models.RolePoJo, 0)

	if params.NameLike != "" {
		check, id := Util.IsNumber(params.NameLike)
		if check {
			whereSql = whereSql + fmt.Sprintf(" and rms_role.id = %d ", id)
		} else {
			whereSql = whereSql + fmt.Sprintf(" and rms_role.name like %q ", ("%"+params.NameLike+"%"))
		}
	}
	if params.Status > -1 {
		whereSql = whereSql + fmt.Sprintf(" and rms_role.status = %d ", params.Status)
	}
	//默认排序
	sortOrder := "ID"
	switch params.SortOrder {
	case "ID":
		sortOrder = "id"
	}
	if params.SortOrder == "desc" {
		sortOrder = "  " + sortOrder
	}
	// 分页查询
	offset := (params.PageNum - 1) * params.PageSize
	query := db.Table("rms_role").Select(" rms_role.*,T1.real_name As creatorName,T2.real_name As updaterName ")
	query = query.Joins(" Inner Join rms_backend_user As T1 on T1.id = rms_role.creator ")
	query = query.Joins(" Inner Join rms_backend_user As T2 on T2.id = rms_role.updater ")
	err := query.Where(whereSql).Count(&total).Limit(params.PageSize).Offset(offset).Order(sortOrder).Find(&data).Error
	if err != nil {
		fmt.Println(err)
	}
	return data, total
}

func (c *RoleDao) Insert(role *models.Role) *models.Role {
	result := db.Create(&role)
	if result.Error == nil {
		return role
	} else {
		zap.L().Error("数据插入失败", zap.Error(result.Error))
		return nil
	}
}

func (c *RoleDao) Get(roleId int64) *models.Role {
	sql := "select *  from rms_role where  id=? "
	role := models.Role{}
	result := db.Raw(sql, roleId).First(&role)
	if result.Error == nil {
		return &role
	} else {
		zap.L().Error("查询出错", zap.Error(result.Error))
		return nil
	}
}

func (c *RoleDao) Update(role *models.Role) bool {
	result := db.Save(&role)
	if result.Error == nil {
		return true
	} else {
		zap.L().Error("数据更新失败", zap.Error(result.Error))
		return false
	}
}
func (c *RoleDao) GetList() []*models.RolePoJo {
	data := make([]*models.RolePoJo, 0)
	err := db.Where(" del_flag = ?", 0).Find(&data).Error
	if err == nil {
		return data
	} else {
		zap.L().Error("数据更新失败", zap.Error(err))
		return nil
	}
}
